package com.teamcalendar.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Posts a message to a URL.
 *
 * @author David Wallin
 */
public class Server {
	public static final String		LOOP_BACK_IP = "10.0.2.2";
	public static final String		SERVER_DOMAIN = "teamcalendar.com";
	public static final String		APPLICATION_CONTEXT = "chatroid";

	public static final String		APPLICATION_COMMAND__REGISTER = "register";
	public static final String		APPLICATION_COMMAND__RETRIEVE = "retrieve";
	public static final String		APPLICATION_COMMAND__SEND = "send";

	public static final String		PARAM__REGISTER_USER__NAME = "name";
	public static final String		PARAM__REGISTER_USER__PASSWORD = "password";

	public static final String		PARAM__SEND_MESSAGE__SENDER_NAME = "sender";
	public static final String		PARAM__SEND_MESSAGE__SENDER_PASSWORD = "password";
	public static final String		PARAM__SEND_MESSAGE__RECIPIENT = "recipient";
	public static final String		PARAM__SEND_MESSAGE__TEXT = "text";

	public static final String		PARAM__RETRIEVE_MESSAGES__NAME = "name";
	public static final String		PARAM__RETRIEVE_MESSAGES__PASSWORD = "password";
	public static final String		PARAM__RETRIEVE_MESSAGES__ALL = "all";

	public static final String		SERVER_RESPONSE__SUCCESSFULLY_REGISTERED = "the new user was successfully registered";
	public static final String		SERVER_RESPONSE__MESSAGE_SENT = "the message was successfully sent";
	public static final String		SERVER_RESPONSE__NO_MESSAGES = "No new messages...";

	public static final String		FROM_PREFIX = "From: ";
	public static final String		DATE_PREFIX = "Sent: ";

	private String                                                  url;
	private Map<String, List<String>>	keyValuePairs;

	public static String getServerWithPort(String url) {
		try {
			InetAddress             inetAddress = InetAddress.getByName(url);
			String                  ipAddress = inetAddress.getHostAddress();
			String                  portExtension = "";

			if(LOOP_BACK_IP.equals(ipAddress)) {
				portExtension = ":8080";
			}

			System.out.println(url + "=" + ipAddress);
			url += portExtension;
		} catch(UnknownHostException e) {
			e.printStackTrace();
		}

		return url;
	}

	public Server(String command) {
		this.url = "http://" + getServerWithPort(SERVER_DOMAIN) + "/" + APPLICATION_CONTEXT + "/" + command;
		this.keyValuePairs = new HashMap<String, List<String>>();
	}

	public BufferedReader post(Map<String, List<String>> keyValuePairs) throws ClientProtocolException, URISyntaxException, IOException {
		this.keyValuePairs = keyValuePairs;

		return post();
	}

	public BufferedReader post() throws URISyntaxException, ClientProtocolException, IOException {
		String          requestUrl = this.url;
		boolean         addedQuestionMark = false;

		for(Entry<String, List<String>> entry : this.keyValuePairs.entrySet()) {
			String                          name = entry.getKey();
			List<String>            values = entry.getValue();

			if(values != null) {
				for(String value : values) {
					if(addedQuestionMark) {
						requestUrl += "&";
					} else {
						requestUrl += "?";
						addedQuestionMark = true;
					}

					requestUrl += (name + "=" + value);
				}
			}
		}

		URI                             uri = new URI(requestUrl);
		HttpPost                post = new HttpPost(uri);

		HttpClient                              client = new DefaultHttpClient();
		HttpResponse                    response = client.execute(post);
		HttpEntity                              entity = response.getEntity();
		InputStream                             inputStream = entity.getContent();
		InputStreamReader               inputStreamReader = new InputStreamReader(inputStream);

		return new BufferedReader(inputStreamReader);
	}

	public void addKeyValuePair(String key, String value) {
		List<String>            values = this.keyValuePairs.get(key);

		if(values == null) {
			values = new ArrayList<String>();
			this.keyValuePairs.put(key, values);
		}

		values.add(value);
	}
}

